#include "userwidget.h"
#include "ui_userwidget.h"
#include "loginwidget.h"
#include "standalonewidget.h"
#include "rankwidget.h"
#include "battlewidget.h"
#include <QMessageBox>
#include <QDebug>
#include <QEventLoop>

UserWidget::UserWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserWidget),
    m_networkAccessManager(Q_NULLPTR)
{
    ui->setupUi(this);

    // 显示用户名
    ui->m_usernameLabel->setText(Global::userId);

    // 退出登录
    connect(ui->m_logoutButton, &QPushButton::clicked, this, [&]() {
        this->close();
        Global::loginWidget->show();
        Global::userWidget = Q_NULLPTR;
    });

    // 单人模式
    connect(ui->m_standaloneButton, &QPushButton::clicked, this, [&]() {
        StandaloneWidget *standaloneWidget = new StandaloneWidget();
        standaloneWidget->show();
        this->hide();
    });

    // 对战模式
    connect(ui->m_battleButton, &QPushButton::clicked, this, [&]() {
        BattleWidget *battleWidget = new BattleWidget();
        battleWidget->show();
        this->hide();
    });

    // 查看排名
    connect(ui->m_rankButton, &QPushButton::clicked, this, [&]() {
        RankWidget *rankWidget = new RankWidget();
        rankWidget->show();
        this->hide();
    });
}

UserWidget::~UserWidget()
{
    delete ui;
}

void UserWidget::closeEvent(QCloseEvent *event)
{
    QEventLoop waitForLogoutLoop;
    if (!m_networkAccessManager)
        m_networkAccessManager = new QNetworkAccessManager(this);
    connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, [&]() {
        waitForLogoutLoop.exit();
    });
    QNetworkRequest request;
    request.setUrl(QUrl(Global::serverIp + QString("/user/logout_user?user_id=%1")
                    .arg(Global::userId)));
    m_networkAccessManager->get(request);
    waitForLogoutLoop.exec();
}
